package com.mzba.place.ui;

import java.util.HashMap;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.view.Window;

import com.google.gson.Gson;
import com.mzba.place.R;
import com.mzba.place.db.UserTable;
import com.mzba.place.entity.RegisterEntity;
import com.mzba.place.utils.AppContext;
import com.mzba.place.utils.HttpUtils;
import com.mzba.place.utils.UrlConfig;
/**
 * Start Activity
 * @author 06peng
 *
 */
public class SplashActivity extends Activity implements Callback {
	
	private final static int load_finish = 1;
	private Handler handler;
	private String deviceId;

	@Override
	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_splash);
		handler = new Handler(this);
		TelephonyManager tm = (TelephonyManager) getSystemService(Activity.TELEPHONY_SERVICE);
		deviceId = tm.getDeviceId();
		new Thread() {
			public void run() {
				register();
			};
		}.start();
	}
	
	private void register() {
		try {
			UserTable ut = new UserTable(this);
			if (ut.get() != null) {
				AppContext.getInstance().setAuthToken(ut.get().getAuthentication_token());
			} else {
				HashMap<String, String> paramsMap = new HashMap<String, String>();
				paramsMap.put("uuid", deviceId);
				String response = HttpUtils.doPost(this, UrlConfig.register, paramsMap);
				if (response != null) {
					Gson gson = new Gson();
					RegisterEntity entity = gson.fromJson(response, RegisterEntity.class);
					if (entity != null) {
						String authToken = entity.getAuthentication_token();
						AppContext.getInstance().setAuthToken(authToken);
						ut.save(entity);
					}
				} 
			}
			handler.sendEmptyMessage(load_finish);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case load_finish:
			Intent intent = new Intent(this, MainActivity.class);
			startActivity(intent);
			finish();
			break;
		default:
			break;
		}
		return false;
	}
	
	
}
